package com.dc.controller;

import com.dc.baseController.BaseController;
import com.dc.em.ErrorMessageEnum;
import com.dc.model.User;
import com.dc.service.UserService;
import com.dc.utils.RSAUtils;
import com.dc.vo.BaseModel;
import com.dc.vo.BusinessException;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiImplicitParam;
import com.wordnik.swagger.annotations.ApiImplicitParams;
import com.wordnik.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/User")
@Api("用户模块")
public class UserController extends BaseController {
    @Autowired
    UserService userService;
    @ApiOperation(value = "分页查查询用户信息",httpMethod = "GET",notes = "查询")
    @RequestMapping(value="/selectPageByName", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前页面",name = "curr_page",defaultValue = "1",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value = "一页的最大条数",name = "page_size",defaultValue = "10",dataType = "Integer",paramType = "query")
    })
    @ResponseBody
    public BaseModel selectPageByName(Integer curr_page,Integer page_size,BaseModel baseModel) throws Exception{
        return userService.selectPageUser(curr_page,page_size,baseModel);
    }
    @ApiOperation(value = "按用户ID查询用户信息",httpMethod = "POST",notes = "查询")
    @RequestMapping(value="/selectUserById/{id}", method = RequestMethod.POST)
    @ResponseBody
    public BaseModel selectUserById(@PathVariable("id") int id ,BaseModel baseModel) throws Exception{
        return userService.selectUserById(id,baseModel);
    }
    @ApiOperation(value = "按用户名查询用户信息",httpMethod = "POST",notes = "查询")
    @RequestMapping(value="/selectPageByName", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户名",name = "name",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "当前页面",name = "curr_page",defaultValue = "1",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value = "一页的最大条数",name = "page_size",defaultValue = "10",dataType = "Integer",paramType = "query")
    })
    @ResponseBody
    public BaseModel selectPageByName(String name,Integer curr_page,Integer page_size,BaseModel baseModel) throws Exception{
        return userService.selectPageByName(name,curr_page,page_size,baseModel);
    }
    //    新增用户
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    @ApiOperation(value="新增用户",httpMethod = "POST",notes = "新增")
    @ApiImplicitParams({
            @ApiImplicitParam(value="账号",name="account",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="密码",name="password",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="姓名",name="name",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="头像地址",name="head_url",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="手机号码",name="phone",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="性别",name="sex",required = true,dataType = "Integer",paramType = "query"),
    })
    @ResponseBody
    public BaseModel addUser(User user, BaseModel baseModel, HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession();
        User currUser = (User) session.getAttribute("currentUser");
        if (currUser == null) {
            throw new BusinessException(ErrorMessageEnum.LOGIN_TIMEOUT);
        }
        user.setIs_deleted(0);
        user.setState(0);
        user.setVersion(0);
        return userService.addUser(user,baseModel);
    }
//    添加一个登录接口,账号必须为手机号码，密码必须超过6位，校验通过，登录成功，否则显示相应错误
@ApiOperation(value="登录",httpMethod = "POST",notes = "登录")
@RequestMapping(value="/login",method = RequestMethod.POST)
@ResponseBody
public BaseModel login(@RequestParam(value = "account",required = false) String account,
                       @RequestParam(value = "password",required = false) String password, BaseModel baseModel, HttpServletRequest request) throws Exception {
    String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9])|(16[6]))\\d{8}$";
    if (!Pattern.matches(regex, account) || password.length() < 6) {
        throw new BusinessException(ErrorMessageEnum.FORMAT_ERROR);
    }
    HttpSession session = request.getSession();
    //pew是一个密文，需要先解密出明文在比对
    String whiltePwd= RSAUtils.sessionDecryptHexStr(session,password);
//            调用业务成
    baseModel = userService.login(account, whiltePwd, baseModel);
//            将登入用户的数据存入到session
    session.setAttribute("currentUser", baseModel.getData());
    return baseModel;
    }
    //    修改用户
    @ApiOperation(value="修改用户",httpMethod = "POST",notes = "修改")
    @RequestMapping(value="/updateUser",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(value="用户id",name="user_id",required = true,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value="账号",name="account",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="密码",name="password",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="姓名",name="name",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="头像地址",name="head_url",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="手机号码",name="phone",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="性别",name="sex",required = false,dataType = "Integer",paramType = "query"),
    })
    @ResponseBody
    public BaseModel updateUser(User user,BaseModel baseModel,HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession();
        User currUser = (User) session.getAttribute("currentUser");
        if (currUser == null) {
            throw new BusinessException(ErrorMessageEnum.LOGIN_TIMEOUT);
        }
        return userService.updateUser(user, baseModel);
    }
    //    修改用户
    @ApiOperation(value="修改用户头像",httpMethod = "POST",notes = "修改")
    @RequestMapping(value="/updateUserPictrue",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(value="用户id",name="user_id",required = true,dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value="账号",name="account",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="密码",name="password",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="姓名",name="name",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="头像地址",name="head_url",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="手机号码",name="phone",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value="性别",name="sex",required = false,dataType = "Integer",paramType = "query"),
    })
    @ResponseBody
    public BaseModel updateUserPhone(User user, BaseModel baseModel, HttpServletRequest request, MultipartFile file) throws Exception{
        HttpSession session = request.getSession();
        User currUser = (User) session.getAttribute("currentUser");
        if (currUser == null) {
            throw new BusinessException(ErrorMessageEnum.LOGIN_TIMEOUT);
        }
        String path = request.getSession().getServletContext().getRealPath("/images");
        System.out.println("路径："+path);
        String fileName = file.getOriginalFilename();
        System.out.println("文件名称"+fileName);
        File dir = new File(path, fileName);
        System.out.println("判断目录是否存在："+dir.exists());
        if(!dir.exists()){
            dir.mkdirs();
        }
//      MultipartFile自带的解析方法
        file.transferTo(dir);
        //这里我在拼接出我图片要显示的url
        String imageurl = "http://localhost:9527/shoes_Web_exploded/images/"+fileName;
        user.setHead_url(imageurl);
        return userService.updateUser(user, baseModel);
    }
    //    删除
    @RequestMapping(value = "/deletedUser/{ids}",method = RequestMethod.POST)
    @ApiOperation(value="删除用户",httpMethod = "POST",notes = "删除")
    @ResponseBody
    public BaseModel deletedUser(@PathVariable(value = "ids") String ids, BaseModel baseModel, HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession();
        User currUser = (User) session.getAttribute("currentUser");
        if(currUser == null){
            throw new BusinessException(ErrorMessageEnum.LOGIN_TIMEOUT);
        }
        return userService.deletedUser(ids,baseModel);
    }
//    修改用户状态
    @RequestMapping(value = "/updateUserState/{id}",method = RequestMethod.POST)
    @ApiOperation(value="修改用户状态",httpMethod = "POST",notes = "修改状态")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "状态", name = "state", required = true, dataType = "int", paramType = "query"),
    })
    @ResponseBody
    public BaseModel updateUserState(@PathVariable("id") int id,int state,BaseModel baseModel,HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        User currUser = (User) session.getAttribute("currentUser");
        if(currUser == null){
            throw new BusinessException(ErrorMessageEnum.LOGIN_TIMEOUT);
        }
        return userService.updateUserState(id,state,baseModel);
    }
    @RequestMapping(value = "/codeLogin",method = RequestMethod.POST)
    @ApiOperation(value="手机号登录",httpMethod = "POST",notes = "查询")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "手机号码", name = "phone", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "验证码", name = "Strcode", required = false, dataType = "String", paramType = "query")
    })
    @ResponseBody
    public BaseModel codeLogin(String phone,String Strcode, BaseModel baseModel,HttpServletRequest request) throws Exception{
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9])|(16[6]))\\d{8}$";
        if (!Pattern.matches(regex, phone)) {
            throw new BusinessException(ErrorMessageEnum.FORMAT_ERROR);
        }
        HttpSession session = request.getSession();
//        String StrCode = (String) session.getAttribute("Strcode");
//        if(!Strcode.equals(StrCode)){
//            throw new BusinessException(ErrorMessageEnum.MESSAGE_ERROR);
//        }
//            将登入用户的数据存入到session
        User user = (User) baseModel.getData();
        session.setAttribute("currentUser", user);
        User currUser = (User) session.getAttribute("currentUser");
        System.out.println(currUser);
        baseModel = userService.codeLogin(phone, baseModel);
        return baseModel;
    }
}
